/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.una.scece.utiles;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.una.scece.control.controlGestor;
/**
 *
 * @author Erick
 */
public class subirArchivo extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // Commons file upload classes are specifically instantiated
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            ServletOutputStream out = null;
            String []datos = null;
            File write = null;
            int i = 0;
            try {
                // Parse the incoming HTTP request
                // Commons takes over incoming request at this point
                // Get an iterator for all the data that was sent
                List items = upload.parseRequest(request);
                datos = new String[items.size()];
                Iterator iter = items.iterator();
                // Set a response content type
                response.setContentType("text/html");
                // Setup the output stream for the return XML data
                out = response.getOutputStream();
                // Iterate through the incoming request data
                while (iter.hasNext()) {
                    // Get the current item in the iteration
                    FileItem item = (FileItem) iter.next();
                    // If the current item is an HTML form field
                    if (item.isFormField()) {
                        // Return an XML node with the field name and value
                        datos[i] = item.getString();
                        i++;
                        out.println("this is a form data " + item.getFieldName() + "<br>");

                    } else {// If the current item is file data
                        String path = "D:\\Prueba\\";
                        File disk = new File(path);
                        disk.mkdirs();
                        String dir = disk.getAbsolutePath() + "\\";
                        write = new File(dir + item.getName());
                        item.write(write);
                        datos[i] = write.getAbsolutePath();
                        i++;
                        // Return an XML node with the file name and size (in bytes)
                        //out.println(getServletContext().getRealPath("/WEB_INF"));
                        //out.println("this is a file with name: " + item.getName());
                    }
                }
                controlGestor.agregarComprobante(datos[1].split("-")[0], datos[0], Date.valueOf(datos[3]), Double.parseDouble(datos[2]),Integer.parseInt(datos[5]), datos[4]);
                response.setStatus(HttpServletResponse.SC_OK);
                // Close off the response XML data and stream
                // Rudimentary handling of any exceptions
                // TODO: Something useful if an error occurs
            } catch (FileUploadException fue) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                fue.printStackTrace();
            } catch (IOException ioe) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                ioe.printStackTrace();
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e.printStackTrace();
            }
            finally{
                out.close();
            }
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
